package com.dkm.orproject.dkmoa.action;

import com.alibaba.fastjson.JSON;
import com.dkm.orproject.dkmoa.domain.OaLog;
import com.dkm.orproject.dkmoa.domain.OaPersonnel;
import com.dkm.orproject.dkmoa.domain.OaTravelBusinessFlow;
import com.dkm.orproject.dkmoa.service.OaTravelBusinessFlowService;
import com.dkm.orproject.utils.jwt.login.UserLoginToken;
import com.dkm.orproject.utils.utils.FileTools;
import com.dkm.orproject.utils.utils.Tools;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *  @ClassName : OaTravelBusinessFlowAction  //类名
 *  @Description : 差旅流程的控制层
 *  @Author : zmh //作者
 *  @Date: 2021-1-20 09:28  //时间
 */
@RestController
@RequestMapping("OaTravelBusinessFlowAction")
public class OaTravelBusinessFlowAction {
    /**
     * 差旅流程的服务层接口
     */
    @Resource
    private OaTravelBusinessFlowService oaTravelBusinessFlowService;

    /**
     * 工具类
     */
    @Resource
    Tools tools;
    @Resource
    FileTools fileTools;
    /**
     * 回调值
     */
    int row = 0;

    /**
     * 日志
     */
    OaLog log;

    /**
     * 登陆人
     */
    OaPersonnel personnel;

    /**
     * 回调map
     */
    Map<String,Object> map;

    /**
     * 查询所有并进行分页
     * @param oaTravelBusinessFlow 差旅模型
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param page 页面
     * @param limit 显示的数量
     * @param request 请求
     * @return
     */
    @UserLoginToken
    @GetMapping("findAll")
    public Map<String, Object> findAll(OaTravelBusinessFlow oaTravelBusinessFlow, String startTime, String endTime, Integer page, Integer limit, HttpServletRequest request) {
        try {
            List<OaTravelBusinessFlow> listFlow;
            Long rowCount;
            //判断是否为查看所有的

            listFlow = oaTravelBusinessFlowService.findAll(oaTravelBusinessFlow, page, limit, startTime, endTime);
            rowCount = oaTravelBusinessFlowService.rowCount(oaTravelBusinessFlow, startTime, endTime);


            return Tools.maps(listFlow, rowCount);
        } catch (Exception e) {
            addErrorLog(request, "差旅流程分页查询", e);
        }
        return null;

    }

    /**
     * 批量删除
     * @param ids 差旅ids
     * @param request 请求
     * @return map
     */
    @UserLoginToken
    @DeleteMapping("deleteAll")
    public Map<String,Object> deleteAll(@RequestParam(value = "ids[]",required = false)Long[] ids,HttpServletRequest request){
        rowMap(request);
        if(ObjectUtils.isEmpty(ids)){
            return tools.rowMap(map,0,null);
        }
        try{
            List<Long> list = Arrays.asList(ids);
            List<OaTravelBusinessFlow> listFlow = oaTravelBusinessFlowService.selectAll(list);
            row = oaTravelBusinessFlowService.deleteAll(list);
            log.setLogTitle("人员差旅删除");
            log.setLogBody(JSON.toJSON(listFlow).toString());
            log.setLogType("1");
            tools.rowMap(map,row,log);
        }catch (Exception e){
            addErrorLog(request,"人员差旅删除",e);
        }
        return map;
    }


    /**
     * 起草人节点
     *
     * @param oaTravelBusinessFlow 差旅流程模型
     * @param request              服务器请求
     * @return 回调函数
     */
    @UserLoginToken
    @PostMapping("apply")
    public Map<String, Object> add(OaTravelBusinessFlow oaTravelBusinessFlow, HttpServletRequest request) {
        //获取当前操作人信息
        rowMap(request);
        //判断登录人是否存在
        if (ObjectUtils.isEmpty(personnel)) {
            return tools.rowMap(map, 0, null);
        }
        try {
            if (oaTravelBusinessFlow.getTravelBusinessFileOne().getOriginalFilename() != null
                            && !"".equals(oaTravelBusinessFlow.getTravelBusinessFileOne().getOriginalFilename())) {
                String path = fileTools.saveFile("TravelBusiness", oaTravelBusinessFlow.getTravelBusinessFileOne());
                oaTravelBusinessFlow.setTravelBusinessFile(path);
            }
            //差旅流程新增
            row = oaTravelBusinessFlowService.add(oaTravelBusinessFlow, personnel);
            //日志标题
            log.setLogTitle("差旅流程新增");
            //日志类型
            log.setLogType("1");
            //日志内容
            log.setLogBody(JSON.toJSON(personnel).toString());
            //新增日志信息 格式化返回信息
            tools.rowMap(map, row, log);
        }catch (Exception e){
            //收集报错信息
            addErrorLog(request,"差旅流程新增",e);
        }
        return map;
    }

    /**
     * 部门领导通过
     * @param request 服务器请求
     * @param pkTravelBusinessId id值
     * @return 回调函数
     */
    @UserLoginToken
    @PostMapping("sectionPass")
    public Map<String,Object> sectionPass(HttpServletRequest request,Long pkTravelBusinessId){
        //获取当前操作人
        rowMap(request);
        //判断当前操作人是否存在
        if(ObjectUtils.isEmpty(personnel)){
            return tools.rowMap(map,0,null);
        }
        try{
            //部门领导通过
            row=oaTravelBusinessFlowService.sectionPass(personnel,pkTravelBusinessId);
            //日志类型
            log.setLogType("1");
            //日志内容
            log.setLogBody(pkTravelBusinessId.toString());
            //新增日志 格式化返回信息
            tools.rowMap(map,row,log);
        }catch (Exception e){
            addErrorLog(request,"部门审核通过",e);
        }
        return map;
    }


    /**
     *  部门领导不通过
     * @param request 服务器请求
     * @param pkTravelBusinessId 审核信息
     * @param formReason 审核意见
     * @return 回调函数
     */
    @UserLoginToken
    @PostMapping("sectionNoPass")
    public Map<String,Object> sectionNoPass(HttpServletRequest request,Long pkTravelBusinessId,String formReason){
        //获取当前操作人
        rowMap(request);
        //判断当前操作人是否存在
        if(ObjectUtils.isEmpty(personnel)){
            return tools.rowMap(map,0,null);
        }
        try{
            //部门领导不通过
            row=oaTravelBusinessFlowService.sectionNoPass(pkTravelBusinessId,personnel,formReason);
            //日志标题
            log.setLogTitle("部门审核不通过");
            //日志类型
            log.setLogType("1");
            //日志内容
            log.setLogBody(formReason);
            //新增日志 格式化返回参数
            tools.rowMap(map,row,log);
        }catch (Exception e){
            //收集报错信息
            addErrorLog(request,"部门审核不通过",e);
        }
        return map;
    }

    /**
     * 人事审核通过
     * @param request 服务器请求
     * @param pkTravelBusinessId 差旅流程id值
     * @return 回调函数
     */
    @UserLoginToken
    @PostMapping("staffingPass")
    public Map<String,Object> staffingPass(HttpServletRequest request,Long pkTravelBusinessId){
        //获取当前操作人
        rowMap(request);
        //判断当前操作人是否存在
        if(ObjectUtils.isEmpty(personnel)){
            return tools.rowMap(map,0,null);
        }
        try{
            //人事审核通过
            row=oaTravelBusinessFlowService.staffingPass(pkTravelBusinessId,personnel);
            //日志标题
            log.setLogTitle("人事审核通过");
            //日志类型
            log.setLogType("1");
            //日志内容
            log.setLogBody(pkTravelBusinessId.toString());
            //记录日志 格式化返回参数
            tools.rowMap(map,row,log);
        }catch (Exception e){
            //收集错误信息
            addErrorLog(request,"人事审核通过",e);
        }
        return map;
    }

    /**
     * 人事审核不通过
     * @param request 服务器请求
     * @param pkTravelBusinessId 差旅
     * @param formReason 不通过原因
     * @return 回调函数
     */
    @UserLoginToken
    @PostMapping("staffingNoPass")
    public Map<String,Object> staffingNoPass(HttpServletRequest request,Long pkTravelBusinessId,String formReason){
        rowMap(request);
        if(ObjectUtils.isEmpty(personnel)){
            return tools.rowMap(map,0,null);
        }
        try{
            row=oaTravelBusinessFlowService.staffingNoPass(pkTravelBusinessId,personnel,formReason);
            log.setLogTitle("人事审核不通过");
            log.setLogType("1");
            log.setLogBody(formReason);
            tools.rowMap(map,row,log);
        }catch (Exception e){
            addErrorLog(request,"人事审核不通过",e);
        }
        return map;
    }
    /**
     * 总经理审核通过
     * @param request 服务器请求
     * @param pkTravelBusinessId 差旅流程id值
     * @return 回调函数
     */
    @UserLoginToken
    @PostMapping("exPass")
    public Map<String,Object> exPass(HttpServletRequest request,Long pkTravelBusinessId){
        //获取当前操作人
        rowMap(request);
        //判断当前操作人是否存在
        if(ObjectUtils.isEmpty(personnel)){
            return tools.rowMap(map,0,null);
        }
        try{
            //人事审核通过
            row=oaTravelBusinessFlowService.exPass(pkTravelBusinessId,personnel);
            //日志标题
            log.setLogTitle("总经理审核通过");
            //日志类型
            log.setLogType("1");
            //日志内容
            log.setLogBody(pkTravelBusinessId.toString());
            //记录日志 格式化返回参数
            tools.rowMap(map,row,log);
        }catch (Exception e){
            //收集错误信息
            addErrorLog(request,"总经理审核通过",e);
        }
        return map;
    }
    /**
     * 总经理不通过
     * @param request 服务器请求
     * @param pkTravelBusinessId 差旅
     * @param formReason 不通过原因
     * @return 回调函数
     */
    @UserLoginToken
    @PostMapping("exNoPass")
    public Map<String,Object> exNoPass(HttpServletRequest request,Long pkTravelBusinessId,String formReason){
        rowMap(request);
        if(ObjectUtils.isEmpty(personnel)){
            return tools.rowMap(map,0,null);
        }
        try{
            row=oaTravelBusinessFlowService.exNoPass(pkTravelBusinessId,formReason,personnel);
            log.setLogTitle("总经理审核不通过");
            log.setLogType("1");
            log.setLogBody(formReason);
            tools.rowMap(map,row,log);
        }catch (Exception e){
            addErrorLog(request,"总经理审核不通过",e);
        }
        return map;
    }
    /**
     * 根据Id删除该条差旅流程的数据接口
     * @param pkOaTravelBusinessFlowId  id值
     * @param request 服务器请求
     * @return 回调函数
     */
    @DeleteMapping("deleteOaTravelBusinessFlowById/{pkOaTravelBusinessFlowId}")
    public Map<String ,Object> deleteOaTravelBusinessFlowById(@PathVariable("pkOaTravelBusinessFlowId")Long pkOaTravelBusinessFlowId, HttpServletRequest request ){
        Map<String,Object> map = new HashMap<>();
        OaPersonnel oaPersonnel = (OaPersonnel)request.getSession().getAttribute("user");
       try{
           OaLog log = new OaLog();
           OaTravelBusinessFlow oaTravelBusinessFlow = new OaTravelBusinessFlow();
           oaTravelBusinessFlow.setPkTravelBusinessId(pkOaTravelBusinessFlowId);
           oaTravelBusinessFlow.setIsRevision("0");
           log.setCreatedBy(oaPersonnel.getPersonnelName());
           log.setLogTitle("差旅流程的删除模块");
           int rows = oaTravelBusinessFlowService.deleteTravelBusinessFlowByPrimaryKey(pkOaTravelBusinessFlowId);
           log.setLogIp(request.getRemoteAddr());
           log.setLogType("1");
           log.setLogBody(JSON.toJSON(oaPersonnel).toString());
           tools.rowMap(map, rows, log);
           return map;
       }catch (Exception e){
           OaLog log = new OaLog();
           log.setLogTitle("差旅流程的删除模块异常");
           log.setLogIp(request.getRemoteAddr());
           log.setLogBody(JSON.toJSON(e.getStackTrace()).toString());
           log.setCreatedBy(oaPersonnel.getPersonnelName());
           log.setLogType("0");
           tools.errorMap(map, log);
           return map;
       }

    }

    /**
     * 根据Id查询接口
     * @param pkOaTravelBusinessFlowId 差旅流程id值
     * @param request 请求对象
     * @return 差旅流程模型
     */
    @GetMapping("findOaTravelBusinessFlowIdById/{pkOaTravelBusinessFlowId}")
    @UserLoginToken
    public Map<String, Object> findOaTravelBusinessFlowIdById(@PathVariable("pkOaTravelBusinessFlowId") Long pkOaTravelBusinessFlowId, HttpServletRequest request) {
        OaPersonnel oaPersonnel = (OaPersonnel) request.getSession().getAttribute("user");
        Map<String, Object> map = new HashMap<>();
        try {
            OaTravelBusinessFlow oaTravelBusinessFlow = oaTravelBusinessFlowService.selectTravelBusinessFlowByPrimaryKey(pkOaTravelBusinessFlowId);
            System.out.println(oaTravelBusinessFlow.toString());
            OaLog log = new OaLog();
            log.setLogTitle("差旅流程根据id查询模块查询成功");
            log.setCreatedBy(oaPersonnel.getPersonnelName());
            log.setLogIp(request.getRemoteAddr());
            log.setLogType("1");
            log.setLogBody(JSON.toJSON(oaPersonnel).toString());
            tools.rowMap(map, 1, null);
            map.put("data", oaTravelBusinessFlow);
            return map;
        } catch (Exception e) {

            OaLog log = new OaLog();
            log.setLogTitle("差旅流程根据id查询模块异常");
            log.setLogBody(JSON.toJSON(e.getStackTrace()).toString());
            log.setCreatedBy(oaPersonnel.getPersonnelName());
            log.setLogType("0");
            log.setLogIp(request.getRemoteAddr());
            tools.errorMap(map, log);
        }
        return map;
    }

    /**
     * 报错日志新增
     * @param request 请求 用于得到当前登录人和ip地址
     * @param title 模块标题
     * @param e 异常参数
     */
    private void addErrorLog(HttpServletRequest request,String title,Exception e){
        //答应日志信息
        e.printStackTrace();
        //获取当前用户信息
        personnel= (OaPersonnel) request.getSession().getAttribute("user");
        //新建日志
        log=new OaLog();
        //日志类型
        log.setLogType("0");
        //日志内容
        log.setLogBody(e.getLocalizedMessage());
        //日志标题
        log.setLogTitle(title);
        //当前请求ip地址
        log.setLogIp(request.getRemoteAddr());
        //判断当前操作人是否存在
        if(ObjectUtils.isEmpty(personnel)){
            //操作人
            log.setCreatedBy(personnel.getPersonnelName());
        }
        //新增报错信息
        tools.errorMap(log);
    }

    /**
     * 优化代码
     * @param request 服务器请求
     */
    private void rowMap(HttpServletRequest request){
        //新建返回Map模型
        map=new HashMap<>(16);
        //获取登陆人信息
        personnel= (OaPersonnel) request.getSession().getAttribute("user");
        //为空则清空map
        if(ObjectUtils.isEmpty(personnel)){
            return;
        }
        //新建日志
        log=new OaLog();
        //得到ip
        log.setLogIp(request.getRemoteAddr());
        //登陆人名称
        log.setCreatedBy(personnel.getPersonnelName());
    }

    /**
     * 日期格式化
     *
     * @param binder 服务器参数转换器
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // true:允许输入空值，false:不能为空值
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}
